package com.situ.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.web.entity.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {
	private IUserService userService = new UserServiceImpl();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String checkCode = req.getParameter("checkCode");
		String sessionCode = (String) req.getSession().getAttribute("checkCode");
		if (null==checkCode || "".equals(checkCode) || checkCode.equalsIgnoreCase(sessionCode)==false) {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}
		String loginName = req.getParameter("loginName");
		String password = req.getParameter("password");
		User user = new User(loginName, Integer.parseInt(password));
		boolean result = false;
		result = userService.login(user);
		if (result) {
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			ServletContext servletContext = getServletContext();
			List<User> list = (List<User>) servletContext.getAttribute("onlineList");
			if (list == null) {
				list = new ArrayList<>();
			}
			list.add(user);
			servletContext.setAttribute("onlineList", list);
//			resp.sendRedirect(req.getContextPath() + "/");
			resp.getWriter().write("<script>window.parent.location.href='/Java1812WebTest1/index.html'</script>");

		} else {
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
		
	}
}
